package cn.tedu.store.product.webapi.service.impl;

import cn.tedu.store.commons.pojo.product.dto.BrandAddNewDTO;
import cn.tedu.store.commons.pojo.product.dto.BrandUpdateDTO;
import cn.tedu.store.commons.pojo.product.entity.Brand;
import cn.tedu.store.commons.pojo.product.entity.HomeBrand;
import cn.tedu.store.commons.pojo.product.vo.BrandListItemVO;
import cn.tedu.store.commons.pojo.product.vo.BrandStandardVO;
import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.web.JsonPage;
import cn.tedu.store.product.webapi.mapper.BrandCategoryMapper;
import cn.tedu.store.product.webapi.mapper.BrandMapper;
import cn.tedu.store.product.webapi.mapper.HomeBrandMapper;
import cn.tedu.store.product.webapi.mapper.SpuMapper;
import cn.tedu.store.product.webapi.repository.IBrandRedisRepository;
import cn.tedu.store.product.service.IBrandService;
import cn.tedu.store.commons.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.List;

@Slf4j
@Service
@DubboService
public class BrandServiceImpl implements IBrandService {

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IBrandRedisRepository brandRedisRepository;
    @Autowired
    private HomeBrandMapper homeBrandMapper;

    @Override
    public void addNew(BrandAddNewDTO brandAddNewDTO) {
        log.debug("开始处理[添加品牌]业务 参数:{}", brandAddNewDTO);
        int count = brandMapper.countByName(brandAddNewDTO.getName());
        if (count != 0) {
            String message = "添加品牌失败,品牌名称已被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewDTO, brand);
        int rows = brandMapper.insert(brand);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        //是推荐品牌则添加到首页推荐品牌表
        if(brand.getIsRecommend() == 1){
            HomeBrand homeBrand = new HomeBrand();
            homeBrand.setBrandId(brand.getId());
            homeBrand.setBrandName(brand.getName());
            homeBrand.setRecommendStatus(1);
            homeBrandMapper.insert(homeBrand);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理[删除品牌]业务 参数:{}", id);
        BrandStandardVO result = brandMapper.getStandardById(id);
        if (result == null) {
            String message = "删除品牌失败,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //判断是否有关联的分类
        {
            int count = brandCategoryMapper.countByBrand(id);
            if (count != 0) {
                String message = "删除失败,该品牌存在关联的分类!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //判断是否有关联的商品
        {
            int count = spuMapper.countByBrand(id);
            if (count != 0) {
                String message = "删除失败,该品牌存在关联的商品!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //执行删除
        int rows = brandMapper.deleteById(id);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        if(result.getIsRecommend() == 1){
            homeBrandMapper.deleteByBrandId(id);
        }
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理[启用品牌]业务 参数:{}", id);
        updateStatusById(id, 1,"enable");
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理[禁用品牌]业务 参数:{}", id);
        updateStatusById(id, 0,"enable");
    }

    @Override
    public void setRecommend(Long id) {
        log.debug("开始处理[推荐品牌]业务 参数:{}", id);
        updateStatusById(id, 1,"isRecommend");
    }

    @Override
    public void setNotRecommend(Long id) {
        log.debug("开始处理[不推荐品牌]业务 参数:{}", id);
        updateStatusById(id, 0,"isRecommend");
    }

    @Override
    public void updateById(Long id, BrandUpdateDTO brandUpdateDTO) {
        log.debug("开始处理[修改品牌信息]业务 参数:{}", brandUpdateDTO);
        BrandStandardVO result = brandMapper.getStandardById(id);
        if (result == null) {
            String message = "修改品牌信息失败,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //执行修改
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateDTO, brand);
        brand.setId(id);
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理[获取品牌详情]业务 参数:{}", id);
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if(queryResult == null){
            String message = "查询品牌详情,访问的资源不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public JsonPage<BrandListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取品牌列表]业务 参数:{},{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        return JsonPage.restPage(brandMapper.list());
    }

    @Override
    public JsonPage<BrandListItemVO> recommendList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取品牌列表]业务 参数: pageSize:{} pageNum:{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        return JsonPage.restPage(brandMapper.recommendList());
    }

    @Override
    public void rebuildCache() {
        log.debug("开始重建品牌缓存...");
        brandRedisRepository.deleteAll();
        log.debug("清除所有旧数据完成...");
        List<BrandListItemVO> list = brandMapper.list();
        log.debug("列表长度:{}",list.size());
        brandRedisRepository.save(list);
        log.debug("品牌列表写入完成...");
        for (BrandListItemVO brandListItemVO : list) {
            Long id = brandListItemVO.getId();
            BrandStandardVO item = brandMapper.getStandardById(id);
            brandRedisRepository.save(item);
        }
        log.debug("品牌详情数据写入完成...");
        log.debug("品牌缓存重建完成!");
    }

    private void updateStatusById(Long id, Integer value,String type){
        String[] enableTips = {"禁用","启用"};
        String[] recommendTips = {"不推荐","推荐"};
        boolean flag = "enable".equals(type);
        String[] tips = flag?enableTips:recommendTips;
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if(queryResult == null){
            String message = "设置"+tips[value]+"品牌失败,该品牌不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if((flag?queryResult.getEnable():queryResult.getIsRecommend()) == value){
            String message = "设置"+tips[value]+"品牌失败,该品牌已经是"+tips[value]+"状态!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Brand brand = new Brand();
        brand.setId(id);
        if(flag){
            brand.setEnable(value);
        }
        else{
            brand.setIsRecommend(value);
            if(value == 1){
                HomeBrand homeBrand = new HomeBrand();
                homeBrand.setBrandId(id);
                homeBrand.setBrandName(queryResult.getName());
                homeBrand.setRecommendStatus(1);
                homeBrandMapper.insert(homeBrand);
            }else{
                homeBrandMapper.deleteByBrandId(id);
            }

        }
        int rows = brandMapper.updateById(brand);
        if(rows != 1){
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }
}
